package utils.utilcode.blankj.com.myapplication;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ArgbEvaluator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.graphics.Color;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import utils.utilcode.blankj.com.myapplication.utils.Constanst;
import utils.utilcode.blankj.com.myapplication.utils.SPUtils;
import utils.utilcode.blankj.com.myapplication.view.MarginDecoration;
import utils.utilcode.blankj.com.myapplication.view.productInfo;

/**
 * Created by Administrator on 2017-12-06.
 */

public class Meue extends AppCompatActivity {
    private RecyclerView mRecyclerView,recycler;
    private productInfo mProductInfo;
    private List<productInfo> productInfoList = new ArrayList();
    private Meue mContext;

    private productInfoAdapter mAdapter;
    private TextView total_number_product, total_money;
    private int totalNumber;
    private float[] mCurrentPosition = new float[2];
    private float totalMoney;
    private    LinearLayout.LayoutParams laParams;
    private ImageView number_bg;
    private RelativeLayout mLinearLayout, rl_meue;
    private ImageView cart;
    private PathMeasure mPathMeasure;
    private LinearLayout lin, rl_dialog;
    private int mPosition;
    private boolean isShow;
    private AlertDialog mAlertDialog;
    private boolean hasMeasured;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.meue_layout);
        this.mContext = this;
        mRecyclerView = (RecyclerView) findViewById(R.id.recycleView);
        recycler= (RecyclerView) findViewById(R.id.recycler);
        initData();
        initView();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new productInfoAdapter(this, productInfoList);
        mRecyclerView.setAdapter(mAdapter);
        //设置Item增加、移除动画
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());

        mRecyclerView.addItemDecoration(new MarginDecoration(this));
        //RecyclerView 的Item宽或者高不会变
        mRecyclerView.setHasFixedSize(true);
        mAdapter.setProductNumber(new productInfoAdapter.Product() {
            @Override
            public void product(int position, int number) {

//                total_number_product.setText(number + "");
            }

            @Override
            public void productPosition(ImageView imageView) {
                cartAnimal(imageView);
            }


        });

        mAdapter.setOnItemClickLitener(new productInfoAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                switch (view.getId()) {
                    case R.id.add:
                        mPosition = position;
                        break;
                    case R.id.jian:
                        totalNumber -= 1;
                        if (totalNumber == 0) {
                            number_bg.setVisibility(View.GONE);
                        }
                        totalMoney -= productInfoList.get(position).money;
                        total_number_product.setText(String.format("%d", totalNumber));
                        total_money.setText(String.format("%s", totalMoney));
                        break;
                }

            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        });
    }

    private void cartAnimal(ImageView imageView) {
        int parent[] = new int[2];
        mLinearLayout.getLocationInWindow(parent);
        int startLoc[] = new int[2];
        imageView.getLocationInWindow(startLoc);
        int endLoc[] = new int[2];
        cart.getLocationInWindow(endLoc);
        Log.e("Meue", "endLoc   " + endLoc[0] + " " + endLoc[1]);

        final ImageView goods = new ImageView(getApplicationContext());
        goods.setImageDrawable(imageView.getDrawable());
        //指定宽高将其添加在父布局
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mLinearLayout.addView(goods, params);

//        相对于父亲,获取起点终点
        float startX = startLoc[0] - parent[0];
        float startY = startLoc[1] - parent[1];

        float toX = endLoc[0] + cart.getWidth() / 3;
        float toY = endLoc[1] - parent[1];

        Path path = new Path();
        path.moveTo(startX, startY);
        path.cubicTo(startX, endLoc[1], endLoc[0], startY, toX, toY + cart.getWidth() / 3);
//        path.quadTo(startX[0], startY, toX, toY+100);      cubicTo
        mPathMeasure = new PathMeasure(path, false);
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, mPathMeasure.getLength());
        valueAnimator.setDuration(1000);
//         匀速插值器
        valueAnimator.setInterpolator(new LinearInterpolator());
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                //得到距离
                float value = (Float) animation.getAnimatedValue();
                // 获取当前点坐标封装到mCurrentPosition
                mPathMeasure.getPosTan(value, mCurrentPosition, null);
                goods.setX(mCurrentPosition[0]);//  goods.setX(mCurrentPosition[0]);
                goods.setY(mCurrentPosition[1]);
            }
        });
        valueAnimator.start();
        //动画监听，动画执行完了移除goods
        valueAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
//                mRelativeLayout.stma

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                mLinearLayout.removeView(goods);
                AnimatorSet animatorSet = new AnimatorSet();
                ObjectAnimator scaleX = ObjectAnimator.ofFloat(cart, "scaleX", 1.5f, 1f);
                ObjectAnimator scaleY = ObjectAnimator.ofFloat(cart, "scaleY", 1.5f, 1f);
                animatorSet.play(scaleX).with(scaleY);
                animatorSet.setDuration(300);
                animatorSet.start();

                totalNumber += 1;
                if (totalNumber == 1)
                    number_bg.setVisibility(View.VISIBLE);
                totalMoney += productInfoList.get(mPosition).money;
                total_number_product.setText(String.format("%d", totalNumber));
                total_money.setText(String.format("%s", totalMoney));
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
    }

    private void initView() {
        //dialogView
        rl_dialog = (LinearLayout) findViewById(R.id.lin_dialog);
        lin = (LinearLayout) findViewById(R.id.lin);
        cart = (ImageView) findViewById(R.id.cart);
        mLinearLayout = (RelativeLayout) findViewById(R.id.rl);
        rl_meue = (RelativeLayout) findViewById(R.id.rl_meue);
        number_bg = (ImageView) findViewById(R.id.number_bg);
        total_number_product = (TextView) findViewById(R.id.total_number_product);
        total_money = (TextView) findViewById(R.id.total_money);
        //clearAll
        findViewById(R.id.clear_all).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                slowChange(laParams, DisplayUtil.dip2px(Meue.this, 0), false);
                isShow=false;
                mAdapter.clearData();
                //总数目，总金额置为0
                totalNumber=0;
                total_number_product.setText(String.format("%d", 0));
                totalMoney=0;
                total_money.setText(String.format("%s", totalMoney));
            }
        });
        cart.setOnClickListener(new View.OnClickListener() {


            @Override
            public void onClick(View view) {
                if (totalNumber != 0) {
                    if (!isShow) {
                        isShow = true;
                        rl_dialog.setVisibility(View.VISIBLE);
                        slowChange(laParams, DisplayUtil.dip2px(Meue.this, 200), isShow);
                    } else {
                        isShow = false;
                        slowChange(laParams, DisplayUtil.dip2px(Meue.this, 0), isShow);
//                        changeCartBg();
//                        rl_dialog.setVisibility(View.GONE);
                    }
                }

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        laParams = (LinearLayout.LayoutParams) rl_dialog.getLayoutParams();
    }

    private void slowChange(final LinearLayout.LayoutParams laParams, int height, final boolean isShow) {
        ValueAnimator valueAnimator = null;
        if (isShow) {
            valueAnimator = ValueAnimator.ofInt(0, height);
        } else {
            valueAnimator = ValueAnimator.ofInt(200, height);
        }
        valueAnimator.setDuration(300);
        // 匀速插值器
        valueAnimator.setInterpolator(new LinearInterpolator());
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int value = (int) animation.getAnimatedValue();
                laParams.height = value;
                rl_dialog.requestLayout();//tv.requestLayout();
            }
        });
        valueAnimator.start();
        valueAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animator) {

            }

            @Override
            public void onAnimationEnd(Animator animator) {
                if (!isShow) {
                    changeCartBg();
                }
            }

            @Override
            public void onAnimationCancel(Animator animator) {

            }

            @Override
            public void onAnimationRepeat(Animator animator) {

            }
        });


    }

    private void changeCartBg() {
        ObjectAnimator translationUp = ObjectAnimator.ofInt(rl_meue,
                "backgroundColor", Color.parseColor("#9c9c9c"), Color.BLACK);
        translationUp.setInterpolator(new DecelerateInterpolator());
        translationUp.setDuration(300);
        translationUp.setEvaluator(new ArgbEvaluator());
        translationUp.start();
    }

    private void showMeueDialog() {

        mAlertDialog = new AlertDialog.Builder(this).create();
        mAlertDialog.show();            //alertDialog.cancel();关闭
        Window win = mAlertDialog.getWindow();
        // 点击外部区域不会消失
        mAlertDialog.setCanceledOnTouchOutside(false);
        //外部区域颜色不变淡

        //设置窗口透明#00000000，要不出问题
        win.setBackgroundDrawableResource(R.color.color_tran);
        WindowManager.LayoutParams lp = win.getAttributes();
        win.setGravity(Gravity.BOTTOM);//最终位置Gravity.LEFT | Gravity.BOTTOM，，，，，top,right,中间
        // lp.alpha = 0.7f;//改变的是整个窗口，最好不要
        lp.width = DisplayUtil.getScreenWidthPixels(this);//宽和屏幕宽一样
        lp.height = lp.WRAP_CONTENT;//设置dialog高度为包裹内容
        Log.e("Meue", "rl_meue" + rl_meue.getHeight());

        lp.y = rl_meue.getHeight();
        win.getDecorView().setPadding(0, 0, 0, 0);//去padding，要不然不会跟父窗体一样宽
//增加一点视觉效果
        win.clearFlags
                (WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        win.setAttributes(lp);
        win.setContentView(R.layout.dialog);
//找到里面的控件
//        win.findViewById(R.id.tv_loading);

    }

    private void initData() {
        //先读缓存

        String productInfo = (String) SPUtils.get(this, Constanst.PRODUCTINFO, "");
//        if (TextUtils.isEmpty(productInfo)) {
        //获取网络上的
        getData();
//        } else {
//            try {
//                Log.e("Meue", "背地");
//                productInfoList = SPUtils.String2Collect(productInfo);
//                for (productInfo info : productInfoList) {
//                    System.out.println(info.toString());
//                }
//
//                //清除信息
////                SPUtils.remove(this,Constanst.PRODUCTINFO);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }

    }

    private void getData() {
        Log.e("Meue", "获取网络数据");
        for (int i = 0; i <= 9; i++) {
            mProductInfo = new productInfo();
            mProductInfo.url = Constanst.URL;
            mProductInfo.maxNumber = 10;
            mProductInfo.money = 1.5f;
            mProductInfo.name = i + "早餐";
            mProductInfo.time = "早餐";
            productInfoList.add(mProductInfo);
        }
        for (int i = 0; i <= 9; i++) {
            mProductInfo = new productInfo();
            mProductInfo.url = Constanst.URL;
            mProductInfo.maxNumber = 10;
            mProductInfo.money = 2.5f;
            mProductInfo.name = i + "午餐";
            mProductInfo.time = "午餐";
            productInfoList.add(mProductInfo);
        }
        for (int i = 0; i <= 9; i++) {
            mProductInfo = new productInfo();
            mProductInfo.url = Constanst.URL;
            mProductInfo.maxNumber = 10;
            mProductInfo.money = 3.5f;
            mProductInfo.name = i + "晚餐";
            mProductInfo.time = "晚餐";
            productInfoList.add(mProductInfo);
        }
        for (int i = 0; i <= 9; i++) {
            mProductInfo = new productInfo();
            mProductInfo.url = Constanst.URL;
            mProductInfo.maxNumber = 10;
            mProductInfo.money = 2.5f;
            mProductInfo.name = i + "午餐";
            mProductInfo.time = "夜宵";
            productInfoList.add(mProductInfo);
        }
        try {
            SPUtils.put(mContext, Constanst.PRODUCTINFO, SPUtils.Collect2String(productInfoList));
        } catch (IOException e) {
            Log.e("Meue", e.getMessage());
            e.printStackTrace();
        }


    }

}
